from PIL import Image
import numpy as np
import os,sys

def ImgToTxt(imgPath):
    bgr = []
    im = Image.open(imgPath)
    im = im.resize((128,128),resample=1)
    im_arr = np.array(im);
    shape = im_arr.shape
    height = shape[0]
    width = shape[1]
    # print((height, width))
    for h in range(0,height):
        for w in range(0,width):
            [b,g,r] = im_arr[h,w]
            bgr.append([h,w]+[b,g,r])
            # print(bgr);
    return bgr

def resultDispose(bgr):
    bgr_bin = []
    result = []
    bgrlen = len(bgr)
    # 转换为二进制
    for i in range(0,bgrlen):
        z = ""
        for j in range(0,5):
            y = "0"*8 # 初始化y，用于设置置0位
            x = bin(bgr[i][j]) # 初始化x
            # print(x)
            pixlen = len(x)
            if j < 2:
                y = y[:10-pixlen] + x[2:]
            else:
                y = x[2:(7 if pixlen >= 7 else pixlen)] + "0"*(0 if pixlen >= 7 else (7 - pixlen))
            if j == 2:
                z = z + "0" + y
            else:
                z += y
        result.append(z)

    bgrlen = len(result)
    bgr_hex = []
    for i in range(0,bgrlen):
        bgr_hex.append(hex(int(result[i],2)))
        bgr_hex[i] = bgr_hex[i].replace("0x","")
    return bgr_hex

if __name__ == '__main__':
    bgr = ImgToTxt("test2.jpg")
    result1 = resultDispose(bgr)
    originfile = open("log_64_hex2.txt", "w")
    # binfile = open("log_64_hex2.txt", "w")
    originfile.write(str(result1))
    # binfile.write(str(result2))
    originfile.close()
    # binfile.close()